<template>
  <div class="container teaching">
    <header class="header-wrap">
      <h3 class="title">发布教研</h3>
    </header>
    <el-form ref="teaching" class="teaching padBtm" :model="formData" :rules="infoRules" label-width="80px">
      <div class="forItemCon">
        <outer-box title="教研信息">
          <div>
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" />
            </el-form-item>
            <!-- {{formData.colTags}} -->
            <el-form-item label="成长分类" prop="growth_classify">
              <!-- 分类学科 -->
              <!-- <el-cascader v-model="formData.subject" :options="subjectList" :props="{ multiple: true, checkStrictly: true ,
                label:'tagsName',value:'tagsId',children:'sub'}"
              clearable />-->

              <el-select
                :value-key="'itemCode'"
                v-model="info.growth_classify"
                @change="changeGrowth_classifyList"
              >
                <el-option
                  v-for="(items,c) in growth_classifyList"
                  :key="c"
                  :value="items"
                  :label="items.itemName"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学段" prop="phase">
              <!-- 栏目标签 -->
              <el-select @change="changePhase" :value-key="'itemCode'" v-model="info.phase">
                <el-option v-for="(items,c) in phaseList" :key="c" :value="items" :label="items.itemName"></el-option>
              </el-select>

            </el-form-item>

            <el-form-item label="学科" prop="subject">
              <!-- 分类学科 -->
              <el-select :value-key="'itemCode'" v-model="info.subject">
                <el-option v-for="(items,c) in subjectList" :key="c" :value="items" :label="items.itemName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分类" prop="colTags">
                <Cascader :value.sync="info.colTags" :children="'sub'" :list="tagsList" />
                <!-- <el-input v-show="false" v-model="formData.colTags"></el-input> -->
              </el-form-item>

              <el-form-item label="标签"  prop="cateTags">
                <!-- {{formData.cateTags}} -->
                <!-- <el-cascader v-show="false" v-model="info.cateTags" /> -->
                <Cascader :value.sync="info.cateTags" :option="{name:'activity',class:'activity'}" :children="'sub'" :list="classifyList" />
                <!--标签 分类标签 -->

              </el-form-item>
            <el-form-item label="时间" prop="startTime">
              <el-date-picker
                :disabled="Boolean(activityId)"
                v-model="timeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>

            <el-form-item label="允许报名" prop="allowSignup">
              <el-switch  :disabled="Boolean(activityId)" v-model="formData.allowSignup" />

              <div class="uploadSelect flBox" v-show="formData.allowSignup">
                <!-- <el-input class="coll_50"  v-model="formData.quorum"></el-input> -->
                <!-- <el-select v-model="formData.quorum" placeholder="设置报名人数">
                      <el-option
                        v-for="(item,i) in options"
                        :key="item.value"
                        :label="item.label"
                        :value="i"
                        ><strong></strong>
                      </el-option>
                </el-select>-->
                <!-- <el-input class="coll_50 padLeft" placeholder="设置参加人员级别" v-model="formData.levelLimit"></el-input> -->
                <el-select
                  :disabled="Boolean(activityId)"
                  v-model="formData.levelLimit"
                  placeholder="设置参加人员级别"
                >
                  <el-option
                    v-for="(item,i) in levelLimitData"
                    :key="i"
                    :label="item.name"
                    :value="item.groupEnum"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>

            <el-form-item
              label="是否允许文件上传"
              label-width="auto"
              prop="allowUpload"
            >
              <el-switch :disabled="Boolean(activityId)" v-model="formData.allowUpload" />
            </el-form-item>

            <el-form-item label="邀请老师" label-width="auto" props="userFollowIPage">
              <el-select
              class="pageSelect"
              ref="activePageSelect"
                :disabled="Boolean(activityId)"
                :value-key="'groupEnum'"
                v-model="formData.userFollowIPage"
                placeholder="点击邀请老师"

              >
              <div slot="prefix"  @click="clickPageSelect" v-if="info.userFollowTotal>info.userFollowIPageOpt.length">
                 <Pagination float="right" :total="info.userFollowTotal" @pagiontaion="userFollowIPage" />
              </div>
                <el-option
                  v-for="(item,i) in info.userFollowIPageOpt"
                  :key="i"
                  :label="item.nickname"
                  :value="item.userId"
                ></el-option>

              </el-select>
            </el-form-item>
          </div>
        </outer-box>

        <outer-box title="上传封面图片">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :show-file-list="false"
            :data="uploadForm"
            :limit="1"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <div v-else class="avatar-uploader-content">
              <i class="el-icon-plus" />
              <p>上传封面图片</p>
              <p>只支持jpg/png格式，不超过2m</p>
            </div>
          </el-upload>
        </outer-box>
        <!-- 默认 一个  -->

        <outer-box title="详细流程">
          <div class="setp">
            <el-form-item prop="stepList">
             <el-input v-model="info.isFromStep" v-show="false" />
            </el-form-item>
            <el-form-item
              class="marginB10"
              :label="'步骤'+(sl+1)+':'"
              v-for="(liv , sl) in stepList"
              :key="sl"
            >
              <!--<el-input v-model='list.title' placeholder="请输入步骤名称"> </el-input> -->
              <!-- <div class="marBtm">
                <el-date-picker v-model="list.startTime" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </div>-->
              <div class="meetAndLive fl" style="width: calc(100% - 85px);">
                <div class="liveList">
                  <div>
                    <el-tag>{{liv | liveTitle }}</el-tag>
                    <span>{{liv.title}}</span>
                  </div>
                  <div class="flex-fl">
                    <CateStr
                      class="fl textHide"
                      :list="liv.cateTags"
                      :str="'  '"
                      style="width:200px"
                    />
                    <!-- <CateStr :list="liv.colTags" /> -->
                    <div
                      class="pad"
                      style="width:100%;padding-left:200px"
                      v-show="liv.startTime"
                    >{{liv.startTime}}-{{liv.endTime}}</div>
                  </div>
                </div>
              </div>
              <el-button v-show="!activityId" class="fl marginT10 marLeft" @click="deleteActivity(sl)">删除</el-button>
            </el-form-item>
            <el-button v-show="!activityId"  @click="addLiveMeeting('添加在线课程')">添加在线课程</el-button>
            <!-- <div><el-button type='primary'>添加步骤</el-button></div> -->
            <el-button v-show="!activityId"  @click="addLiveMeeting('添加在线会议')">添加在线会议</el-button>

            <el-dialog
              :title="liveVisibleTitle"
              class="t-center"
              :close-on-click-modal="false"
              :visible.sync="liveVisible"
              :before-close="handleClose"
              width="800px"
            >

              <AddLiveActyForm
                v-if="liveVisibleTitle"
                @addActivityLiveFn="addActivityLiveFn"
                :list.sync="stepInit"
                :classifyListArr="classifyListArr"
                :title="liveVisibleTitle"
              />
            </el-dialog>
          </div>
        </outer-box>
        <outer-box title="教研介绍">
          <div>
            <editor v-model="formData.intro" @input="introContent" />
          </div>
        </outer-box>
      </div>
      <el-button>预览</el-button>
      <el-button type="primary" @click="pushNow">{{activityId?'保存':'立即发布'}}</el-button>
      <!-- <el-button type="primary" @click="pushNow">立即发布</el-button> -->
      <!-- <el-button type="primary" @click="goNext">下一步</el-button> -->
    </el-form>
  </div>
</template>

<script>
import outerBox from "@/components/outerBox";
import CateStr from "@/components/cateStr";
import { teacherTarget } from "@/utils/cateTagColumn";
import AddLiveActyForm from "./components/addLiveActyForm";
import { findColumnList, findTagsList, listByKind } from "@/api/basic";
import Pagination from '@/components/Pagination'
import {
  publish,
  userFollowIPage,
  getTeachingResearchDetail,
  teachingResearchUpdate,
} from "@/api/activity";
import Cascader from "@/components/Cascader";
import { preUpload } from "@/api/uploads";
import editor from "@/components/Tinymce/index";
import {
  reduceArr,
  tagsObjSwitch,
  assignment,
  compose,
} from "@/utils/categoryOrTags";

import { arrTreeToArr } from "@/utils/cateTagColumn";
export default {
  components: {
    outerBox,
    editor,
    Pagination,
    AddLiveActyForm,
    Cascader,
    CateStr,
  },
  filters: {
    liveTitle(val) {
     // console.log("val", val);
      return val.stepTypeEnum === "LIVE" ? "在线课程" : "在线会议";
    },
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + "preUpload/form", // 'https://yes910-pub.obs.cn-south-1.myhuaweicloud.com',
      uploadForm: {},
      listQuery:{
       pager: this.$store.state.app.pager
      },
      activityId: this.$route.query.activityId,

      info: {
        growth_classify:{},
        phase: {},
        subject: {},
        colTags: [],
        isFromStep:'',
        cateTags: [],
        stepList: "", //是否添加活动或者在线课程
        userFollowIPageOpt: [],
        userFollowTotal:0,
      },
      options: [
        {
          groupEnum: "STAGE",
          itemCode: "1202",
        },
        {
          groupEnum: "SUBJECT",
          itemCode: "1128",
        },
      ],
      infoRules: {
        title: [
          {
            required: true,
            message: "请填写标题",
          },
        ],
        cateTags: [
          {
            type:'array',
            required: true,
            message: "请填写标签",
          },
        ],
        colTags: [
          {
            type:'array',
            required: true,
            message: "请填写分类",
          },
        ],
        // "coverImageUrl": "",
        endTime: [
          {
            required: true,
            message: "请填写结束时间",
          },
        ],
        intro: [
          {
            required: true,
            message: "请填写介绍内容",
          },
        ],
        // "quorum": 0,
        startTime: [
          {

            required: true,
            message: "请填写开始时间",
          },
        ],
        stepList: [
          { type:'array',
            required: true,
            message: "请填写教研步骤",
          },
        ],
      },
      liveVisible: false,
      liveVisibleTitle: "",
      liveVisibletype: "LIVE",
      stepList: [], //显示的 步骤数据
      paramStep: [], //提交的 步骤数据
      imageUrl: "",
      stepInit: {
        cateTags: [],
        colTags: [],
        endTime: "",
        //"quorum": 0,
        startTime: "",
        stepId: 0,
        stepTypeEnum: "", //MEETING
        title: "",
      },
      mountestepList: {
        cateTags: [],
        colTags: [],
        endTime: "",

        startTime: "",
        stepId: 0,
        stepTypeEnum: "", //MEETING
        title: "",
      },
      formData: {
        activityId: this.$route.query.activityId,
        title: "",
        allowSignup: false,
        allowUpload: false,
        cateTags: [],
        colTags: [],
        coverImageUrl: "",
        endTime: "",
        intro: "",
        levelLimit: "",
        invitedUserIds: "",

        // "quorum": 0,
        startTime: "",
        stepList:'',
        endTime:'',
        categoryList: [],
      },
      tagsList: [],
      timeRange: "",
      phaseList: [],
      subjectList: [],
      growth_classifyList:[],
      levelLimitData: [],
      teachingTargetList: [],
    };
  },
  computed: {
    classifyListArr(){
      let {growth_classify,subject,phase} = this.info
      let stageId = phase?phase.itemCode:''
      let growthClassify = growth_classify?growth_classify.itemCode:''
      let subjectId = subject?subject.itemCode:''
      return {
        growthClassify,
        stageId,
        subjectId
        }
    },
    classifyList() {
      var classifyList = this.$store.state.app.cateTagsGroupFindList;
      // classifyList.map((list) => {
      //   list.tagsId = list.groupId;
      //   list.tagsName = list.groupName;
      //   return (list.sub = list.tagsVoList);
      // });
      return classifyList;
    },
  },
  watch: {
    ['info.colTags'](val){
      this.formData.colTags =val
    },
    ['info.cateTags'](val){
      this.formData.cateTags =val
    },
    ["stepList"](val) {
        this.formData.stepList = val
        this.info.isFromStep = val.length
    },
    ["info.subject"](val) {
      if (val.itemCode) {
        this.formData.categoryList[2]={
          itemCode: val.itemCode,
          groupEnum: val.groupEnum,
        }
        this._findTagsList()
        this._cateTagsGroupFindList()
      }
    },
    ["info.phase"](val) {
      if (val.itemCode) {
        this.formData.categoryList[1]={
          itemCode: val.itemCode,
          groupEnum: val.groupEnum,
        }
         this.getSubject(val.cateId);
        this._findTagsList()
        this._cateTagsGroupFindList()
      }
    },
    ["info.growth_classify"](val) {
      if (val.itemCode) {

       this.formData.categoryList[0]={
          itemCode: val.itemCode,
          groupEnum: val.groupEnum,
        }
         this.getPhase(val.cateId);
        this._findTagsList()
        this._cateTagsGroupFindList()
      }
    },
    timeRange(val) {
      if (val) {
        this.formData.startTime = val[0];
        this.formData.endTime = val[1];
      }
    },
  },
  created() {
    //  const teaLoc = this.getLoc('teach_formData') 获取本地存储

    this._listByKindAcademic();

    this.userFollowIPage();
    // this.getSubject()
    this.getGrowth_classifyList();
    // this._findTagsList()
    const { activityId } = this;
    if (activityId) {
      this.init(activityId);
      this.infoRules.stepList[0].required = false
    }
    this._cateTagsGroupFindList();
    this._findTagsList();
  },
inject:  ['reload'],
  mounted() {},
  beforeRouteLeave(to, form, next) {
    this.setLoc("teach_formData", this.formData);
    next();
  },
  methods: {
    blankSelect(dataOpt, resInfo, tagsId) {
      //分类渲染data， 原cate数据 , selectDate回选v-model ,
      dataOpt = assignment(dataOpt);
      var selectDate = [];
      if (resInfo && resInfo.length > 0) {
        var colTagsArr = reduceArr(dataOpt);
         //console.log("colTagsArr",colTagsArr);
        resInfo.map((item) => {
          const items = colTagsArr.filter((colTag) => {
           if(colTag[tagsId] == item[tagsId]){
             console.log('slecarat',colTag.selectArr)
              selectDate.push(colTag.selectArr);
           }
          })[0];
          // if (items) {
          //   selectDate.push(items.selectArr);
          //   console.log("萨达", selectDate);
          // }
        });
      }
      return selectDate;
    },
    init(activityId) {
      getTeachingResearchDetail({
        activityId,
      }).then((res) => {
        var datas = res.data;
        this.getBlackSubjectId(datas.categoryList, "phase", "STAGE");
        this.getBlackSubjectId(
          datas.categoryList,
          "growth_classify",
          "GROWTH_CLASSIFY"
        );
        this.getBlackSubjectId(datas.categoryList, "subject", "SUBJECT");

        this.info.cateTags = this.blankSelect(
          this.classifyList,
          datas.cateTags,
          "tagsId"
        );
        this.info.colTags = this.blankSelect(
          this.tagsList,
          datas.colTags,
          "tagsId"
        );
        console.log(
          "adfa ",
          this.info.cateTags,
          this.info.colTags,
          this.classifyList
        );

        this.formData.title = datas.title;
        this.timeRange = [datas.startTime, datas.endTime];
        this.formData.intro = datas.intro;
        this.formData.allowSignup = datas.allowSignup;
        this.formData.coverImageUrl = datas.coverImageUrl;
        this.imageUrl = datas.coverImageUrl;
        this.formData.invitedUserIds = datas.invitedUserIds;
        this.formData.allowUpload = datas.allowUpload;
        //this.formData.teachingTarget = datas.teachingTarget //邀请老师


        this.formData.levelLimit = datas.levelLimit; //设置参加人员级别
        // this.formData.userFollowIPage = datas.participantCount
        //活动 会议 在线课程
        this.stepList = datas.stepList ? datas.stepList : [];

        this.listData = res.data;
        console.log("教研详情:", res.data);

        // this.getPlayBack()
        // this.getEnroll()
        // this.getCommentPage()
      });
    },
    changeGrowth_classifyList(item) {
      this.getPhase(item.cateId);
    },
    changePhase(item) {
      this.getSubject(item.cateId);
    },
    clickPageSelect(){
     // this.$refs.activePageSelect.visible = true
     var that = this.$refs.activePageSelect
     that.$refs.popper.visibleArrow = true
     that.$refs.popper.showPopper = true
      debugger
    },
    async userFollowIPage(page = 1, pageSize = 10){
      //this.listQuery.pager =
      let res = await userFollowIPage( {page,pageSize});
      this.info.userFollowIPageOpt = res.data.records;
      this.info.userFollowTotal = res.data.total

    },
    getBlackSubjectId(categoryList, subjects, GROWTH_CLASSIFY) {
      if(categoryList.length){
        var cateList = categoryList.filter(
          (list) => list.groupEnum === GROWTH_CLASSIFY
        )[0];
        //
        if(cateList){
          this.info[subjects] = cateList;
          this.formData[subjects] = cateList;
        }

      }

    },
    async getGrowth_classifyList() {
      let res = await this.$store.dispatch("app/findByParentpCateId", {
        bizTypeEnum: "TEACHINGRESEARCH",
        pCateId: 0,
      });
      this.growth_classifyList = res.categoryVoList;
      this.getPhase(res.categoryVoList[0].cateId);
    },
    async getPhase(pCateId) {
      let res = await this.$store.dispatch("app/findByParentpCateId", {
        bizTypeEnum: "TEACHINGRESEARCH",
        pCateId,
      });
      this.phaseList = res.categoryVoList;
      //this.getSubject(res.categoryVoList[0].cateId);
    },
    async getSubject(pCateId) {
      let res = await this.$store.dispatch("app/findByParentpCateId", {
        bizTypeEnum: "TEACHINGRESEARCH",
        pCateId,
      });
      //let res = await this.$store.dispatch('app/findByParentpCateId',{bizTypeEnum: 'TEACHINGRESEARCH',pCateId: 0})
      this.subjectList = res.categoryVoList;
    },
    introContent() {},
    addLiveMeeting(name) {
      if (name.indexOf("会议") > -1) {
        this.stepInit.quorum = null;
        // this.stepInit =
      }
      this.indTabName = name;
      this.liveVisible = true;
      this.liveVisibleTitle = name;
    },
    handleClose() {
      this.liveVisible = false;
    },
    deleteActivity(i, id) {
      this.stepList.splice(i, 1);
    },
    addActivityLiveFn(list, nameList) {
      // this.list = list
      console.log(list.stepTypeEnum);

      this.liveVisible = false;
      let paramStepObj = { ...list };
      this.$set(this, "stepInit", this.mountestepList); ////清空上一次选择的
      //处理 步骤的params
      paramStepObj.cateTags = arrTreeToArr(list.cateTags);
      paramStepObj.colTags = arrTreeToArr(list.colTags);
      //处理现实
      // list.stepTypeEnum==='LIVE'?'在线课程':'会议'
      this.paramStep.push(paramStepObj);

      if (Array.isArray(this.stepList)) {
        this.stepList.push(nameList);
      } else {
        this.stepList = [];
        this.stepList.push(nameList);
      }

      console.log("lsit", this.stepList);
      //
    },
    async _listByKindAcademic() {
      //人员级别
      const data = teacherTarget; //await listByKind('academic')
      this.levelLimitData = data;
      this.formData.levelLimit = data[0].value;
    },
    _cateTagsGroupFindList() {
      const params = {
        tagsBizEnum: "TEACHINGRESEARCH", //教案
        ...this.classifyListArr
      };
      this.$store.dispatch("app/_cateTagsGroupFindList", params);
    },
    searchAdd() {},
    filterAdd(node, keyword) {
      console.log("key", node, keyword);
    },

    async _findTagsList() {
      const params = {
        ...this.classifyListArr
      };
      const res = await findColumnList(params);
      this.tagsList = res.data;
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log("sda", res, file.raw, this.formData);
    },
    pushNow() {
      var that = this;
      that.formInfo = {}
      Object.assign(that.formInfo,{...this.formData})
      this.formInfo.stepList = this.paramStep;
      that.formInfo.cateTags = arrTreeToArr(
        that.info.cateTags,
        "tagsId",
        "tagsName"
      );

      that.formInfo.colTags = arrTreeToArr(that.info.colTags);
      //var categoryList = [ that.formData.teachingTarget,that.formData.phase,that.formData.subject]
    //  that.formInfo.categoryList = categoryList

      this.$refs.teaching.validate(async (val) => {
        if (val) {
          var res;
          if (this.activityId) {
            var formInfo = {
              activityId: that.formData.activityId,
              cateTags: that.formInfo.cateTags,
              colTags: that.formInfo.colTags,
              coverImageUrl: that.formData.coverImageUrl,
              endTime: that.formInfo.endTime,
              intro: that.formInfo.intro,
              //phase: that.formData.phase,
              startTime: that.formData.startTime,
              categoryList:this.formInfo.categoryList,
              title: that.formInfo.title,
            };
            res = await teachingResearchUpdate(formInfo);
            // delete that.formInfo['stepList']
          } else {
            res = await publish(that.formInfo);
          }
          if (res.code === "1") {
          //window.location='/activity/activity'
          that.$router.push({ name: "ActivityList" })
          }
        }
      });
    },
    async _findTagsList() {
      const params = {
        ...this.classifyListArr
      };
      const res = await findColumnList(params);
      this.tagsList = res.data;
     // console.log(this.tagsList);
    },
    async beforeAvatarUpload(file) {
      //

      const isLt2M = file.size / 1024 / 1024 < 2;

     const imgStr = /\.(jpg|jpeg|png|JPG|PNG|JPEG)$/;
      if (!imgStr.test(file.name)) {
        this.$message.error('上传格式不对，请重新上传!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      let params = {
        biz: "OPEN",
        name: file.name,
        size: file.size,
      };
      let upRes = await preUpload(params);
      this.action = upRes.data.action;
      let data = upRes.data;
      // upRes.data.parameters.token =
      this.uploadForm = data.parameters;
      this.formData.coverImageUrl = data.uri;
      // this.imageUrl// = data.signatureUrl
      return imgStr.test(file.name) && isLt2M;
    },
  },
};
</script>
<style lang="scss">
  .pageSelect{
    .el-input__prefix{
       // display: none;
        left:100%;
      }

    // .el-input--suffix.is-focus{
    //   .el-input__prefix{
    //     display: block;
    //     left:100%;
    //   }
    // }

  }

</style>
<style lang="scss" scoped>
.container {
  padding: 0 40px;

  .header-wrap {
    .title {
      font-size: 20px;
      color: #000;
      line-height: 124px;
      height: 124px;
    }
  }
}

.teaching {
  .setp {
    .el-input {
      margin: 15px 0;
    }
  }
}
/deep/ .liveList {
  line-height: 1.5;
  border-radius: 5px;
  padding: 5px;
  border: solid 1px #e5e6e6;
}
/deep/.el-form-item {
  width: 700px;
}

/deep/.el-cascader {
  width: 620px;
}

/deep/.el-date-editor {
  width: 620px;
}

.avatar-uploader {
  width: 480px;
  height: 270px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-content {
  color: #8c939d;
  width: 480px;
  min-height: 270px;
  text-align: center;
  padding-top: 100px;

  i {
    font-size: 28px;
  }
}

.avatar {
  width: auto;
  height: 100%;
  display: block;
  margin: 0 auto;
}
</style>
